@{
    ViewData["Title"] = "新增生产计划";
}

<link href="~/layui/css/layui.css" rel="stylesheet" />

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <div class="row align-items-center">
                        <div class="col-md-6">
                            <h5 class="mb-0">
                                <i class="layui-icon layui-icon-form"></i>
                                新增生产计划
                            </h5>
                        </div>
                        <div class="col-md-6 text-end">
                            <button type="button" class="btn btn-secondary" onclick="goBack()">
                                <i class="layui-icon layui-icon-return"></i>
                                返回
                            </button>
                        </div>
                    </div>
                </div>
                
                <div class="card-body">
                    <form id="productionPlanForm">
                        <!-- 基本信息 -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <h6 class="border-bottom pb-2 mb-3">
                                    <i class="layui-icon layui-icon-form"></i>
                                    基本信息
                                </h6>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="planSubject" class="form-label">计划主题 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="planSubject" name="planSubject" 
                                       placeholder="请输入计划主题" required>
                            </div>
                            <div class="col-md-6">
                                <label for="planOrderNumber" class="form-label">计划单号 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="planOrderNumber" name="planOrderNumber" 
                                       placeholder="请输入计划单号" required>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="salesOrderNumber" class="form-label">销售订单号</label>
                                <input type="text" class="form-control" id="salesOrderNumber" name="salesOrderNumber" 
                                       placeholder="请输入销售订单号">
                            </div>
                            <div class="col-md-6">
                                <label for="relatedProjectName" class="form-label">关联项目</label>
                                <input type="text" class="form-control" id="relatedProjectName" name="relatedProjectName" 
                                       placeholder="请输入关联项目名称">
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="productionLine" class="form-label">生产线</label>
                                <input type="text" class="form-control" id="productionLine" name="productionLine" 
                                       placeholder="请输入生产线">
                            </div>
                            <div class="col-md-6">
                                <label for="documentDate" class="form-label">单据日期 <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" id="documentDate" name="documentDate" required>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="expectedStartDate" class="form-label">计划开始时间 <span class="text-danger">*</span></label>
                                <input type="datetime-local" class="form-control" id="expectedStartDate" name="expectedStartDate" required>
                            </div>
                            <div class="col-md-6">
                                <label for="expectedEndDate" class="form-label">计划结束时间 <span class="text-danger">*</span></label>
                                <input type="datetime-local" class="form-control" id="expectedEndDate" name="expectedEndDate" required>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="priority" class="form-label">优先级 <span class="text-danger">*</span></label>
                                <select class="form-select" id="priority" name="priority" required>
                                    <option value="">请选择优先级</option>
                                    <option value="1">低</option>
                                    <option value="2">中</option>
                                    <option value="3">高</option>
                                    <option value="4">紧急</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="remarks" class="form-label">备注</label>
                                <textarea class="form-control" id="remarks" name="remarks" rows="3" 
                                          placeholder="请输入备注信息"></textarea>
                            </div>
                        </div>

                        <!-- 生产项目 -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <h6 class="border-bottom pb-2 mb-3">
                                    <i class="layui-icon layui-icon-list"></i>
                                    生产项目
                                    <button type="button" class="btn btn-sm btn-primary ms-2" onclick="addProductionItem()">
                                        <i class="layui-icon layui-icon-add-1"></i>
                                        添加项目
                                    </button>
                                </h6>
                            </div>
                        </div>
                        
                        <div class="table-responsive mb-3">
                            <table class="table table-bordered" id="productionItemsTable">
                                <thead class="table-light">
                                    <tr>
                                        <th width="120">项目编号</th>
                                        <th width="150">项目名称</th>
                                        <th width="120">规格型号</th>
                                        <th width="80">单位</th>
                                        <th width="100">物品分类</th>
                                        <th width="100">物品类别</th>
                                        <th width="100">品牌</th>
                                        <th width="100">数量</th>
                                        <th width="80">排序</th>
                                        <th width="80">操作</th>
                                    </tr>
                                </thead>
                                <tbody id="productionItemsBody">
                                    <!-- 动态添加的生产项目行 -->
                                </tbody>
                            </table>
                        </div>

                        <!-- 附件信息 -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <h6 class="border-bottom pb-2 mb-3">
                                    <i class="layui-icon layui-icon-upload"></i>
                                    附件信息
                                    <button type="button" class="btn btn-sm btn-primary ms-2" onclick="addAttachment()">
                                        <i class="layui-icon layui-icon-add-1"></i>
                                        添加附件
                                    </button>
                                </h6>
                            </div>
                        </div>
                        
                        <div class="table-responsive mb-3">
                            <table class="table table-bordered" id="attachmentsTable">
                                <thead class="table-light">
                                    <tr>
                                        <th width="200">文件名</th>
                                        <th width="100">文件大小</th>
                                        <th width="200">文件路径</th>
                                        <th width="100">文件类型</th>
                                        <th width="80">操作</th>
                                    </tr>
                                </thead>
                                <tbody id="attachmentsBody">
                                    <!-- 动态添加的附件行 -->
                                </tbody>
                            </table>
                        </div>

                        <!-- 操作按钮 -->
                        <div class="row">
                            <div class="col-12 text-center">
                                <button type="button" class="btn btn-primary me-3" onclick="saveProductionPlan()">
                                    <i class="layui-icon layui-icon-ok"></i>
                                    保存
                                </button>
                                <button type="button" class="btn btn-secondary" onclick="resetForm()">
                                    <i class="layui-icon layui-icon-refresh"></i>
                                    重置
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

@section Scripts {
    <script>
        let productionItemIndex = 0;
        let attachmentIndex = 0;

        // 页面加载完成后初始化
        $(document).ready(function() {
            initializeForm();
        });

        // 初始化表单
        function initializeForm() {
            // 设置默认日期
            const today = new Date();
            const tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000));
            
            $('#documentDate').val(today.toISOString().split('T')[0]);
            $('#expectedStartDate').val(today.toISOString().slice(0, 16));
            $('#expectedEndDate').val(tomorrow.toISOString().slice(0, 16));
            
            // 添加一个默认的生产项目行
            addProductionItem();
        }

        // 添加生产项目
        function addProductionItem() {
            const row = `
                <tr id="productionItem_${productionItemIndex}">
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="productionItems[${productionItemIndex}].itemNumber" 
                               placeholder="项目编号">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="productionItems[${productionItemIndex}].itemName" 
                               placeholder="项目名称">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="productionItems[${productionItemIndex}].specificationModel" 
                               placeholder="规格型号">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="productionItems[${productionItemIndex}].unit" 
                               placeholder="单位">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="productionItems[${productionItemIndex}].itemCategory" 
                               placeholder="物品分类">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="productionItems[${productionItemIndex}].itemClassification" 
                               placeholder="物品类别">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="productionItems[${productionItemIndex}].brand" 
                               placeholder="品牌">
                    </td>
                    <td>
                        <input type="number" class="form-control form-control-sm" 
                               name="productionItems[${productionItemIndex}].quantity" 
                               placeholder="数量" min="0">
                    </td>
                    <td>
                        <input type="number" class="form-control form-control-sm" 
                               name="productionItems[${productionItemIndex}].sortOrder" 
                               placeholder="排序" min="0" value="${productionItemIndex}">
                    </td>
                    <td>
                        <button type="button" class="btn btn-sm btn-danger" 
                                onclick="removeProductionItem(${productionItemIndex})">
                            <i class="layui-icon layui-icon-delete"></i>
                        </button>
                    </td>
                </tr>
            `;
            $('#productionItemsBody').append(row);
            productionItemIndex++;
        }

        // 删除生产项目
        function removeProductionItem(index) {
            $(`#productionItem_${index}`).remove();
        }

        // 添加附件
        function addAttachment() {
            const row = `
                <tr id="attachment_${attachmentIndex}">
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="attachments[${attachmentIndex}].fileName" 
                               placeholder="文件名">
                    </td>
                    <td>
                        <input type="number" class="form-control form-control-sm" 
                               name="attachments[${attachmentIndex}].fileSize" 
                               placeholder="文件大小" min="0">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="attachments[${attachmentIndex}].filePath" 
                               placeholder="文件路径">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="attachments[${attachmentIndex}].fileType" 
                               placeholder="文件类型">
                    </td>
                    <td>
                        <button type="button" class="btn btn-sm btn-danger" 
                                onclick="removeAttachment(${attachmentIndex})">
                            <i class="layui-icon layui-icon-delete"></i>
                        </button>
                    </td>
                </tr>
            `;
            $('#attachmentsBody').append(row);
            attachmentIndex++;
        }

        // 删除附件
        function removeAttachment(index) {
            $(`#attachment_${index}`).remove();
        }

        // 保存生产计划
        function saveProductionPlan() {
            // 表单验证
            if (!validateForm()) {
                return;
            }

            // 收集表单数据
            const formData = collectFormData();
            
            // 显示加载状态
            showLoading();

            // 发送请求
            $.ajax({
                url: 'http://localhost:5025/api/Plan/AddProductionPlan',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                timeout: 10000,
                success: function(response) {
                    console.log('API响应:', response);
                    
                    if (response.code === 200) {
                        showSuccess('生产计划创建成功！');
                        setTimeout(() => {
                            window.location.href = '/Home/GetProductionPlan';
                        }, 1500);
                    } else {
                        showError('创建失败：' + (response.msg || '未知错误'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('API请求失败:', {xhr, status, error});
                    showError('请求失败：' + error);
                },
                complete: function() {
                    hideLoading();
                }
            });
        }

        // 表单验证
        function validateForm() {
            const requiredFields = [
                { id: 'planSubject', name: '计划主题' },
                { id: 'planOrderNumber', name: '计划单号' },
                { id: 'documentDate', name: '单据日期' },
                { id: 'expectedStartDate', name: '计划开始时间' },
                { id: 'expectedEndDate', name: '计划结束时间' },
                { id: 'priority', name: '优先级' }
            ];

            for (let field of requiredFields) {
                const value = $(`#${field.id}`).val().trim();
                if (!value) {
                    showError(`请填写${field.name}`);
                    $(`#${field.id}`).focus();
                    return false;
                }
            }

            // 验证日期逻辑
            const startDate = new Date($('#expectedStartDate').val());
            const endDate = new Date($('#expectedEndDate').val());
            
            if (startDate >= endDate) {
                showError('计划结束时间必须晚于开始时间');
                $('#expectedEndDate').focus();
                return false;
            }

            return true;
        }

        // 收集表单数据
        function collectFormData() {
            const formData = {
                planSubject: $('#planSubject').val().trim(),
                planOrderNumber: $('#planOrderNumber').val().trim(),
                documentDate: new Date($('#documentDate').val()).toISOString(),
                remarks: $('#remarks').val().trim(),
                salesOrderNumber: $('#salesOrderNumber').val().trim(),
                relatedProjectName: $('#relatedProjectName').val().trim(),
                expectedStartDate: new Date($('#expectedStartDate').val()).toISOString(),
                expectedEndDate: new Date($('#expectedEndDate').val()).toISOString(),
                productionLine: $('#productionLine').val().trim(),
                priority: parseInt($('#priority').val()),
                productionItems: [],
                attachments: []
            };

            // 收集生产项目数据
            $('#productionItemsBody tr').each(function() {
                const row = $(this);
                const item = {
                    itemNumber: row.find('input[name*="itemNumber"]').val().trim(),
                    itemName: row.find('input[name*="itemName"]').val().trim(),
                    specificationModel: row.find('input[name*="specificationModel"]').val().trim(),
                    unit: row.find('input[name*="unit"]').val().trim(),
                    itemCategory: row.find('input[name*="itemCategory"]').val().trim(),
                    itemClassification: row.find('input[name*="itemClassification"]').val().trim(),
                    brand: row.find('input[name*="brand"]').val().trim(),
                    quantity: parseInt(row.find('input[name*="quantity"]').val()) || 0,
                    sortOrder: parseInt(row.find('input[name*="sortOrder"]').val()) || 0
                };
                
                // 只添加有内容的项目
                if (item.itemNumber || item.itemName) {
                    formData.productionItems.push(item);
                }
            });

            // 收集附件数据
            $('#attachmentsBody tr').each(function() {
                const row = $(this);
                const attachment = {
                    fileName: row.find('input[name*="fileName"]').val().trim(),
                    fileSize: parseInt(row.find('input[name*="fileSize"]').val()) || 0,
                    filePath: row.find('input[name*="filePath"]').val().trim(),
                    fileType: row.find('input[name*="fileType"]').val().trim()
                };
                
                // 只添加有内容的附件
                if (attachment.fileName) {
                    formData.attachments.push(attachment);
                }
            });

            return formData;
        }

        // 重置表单
        function resetForm() {
            if (confirm('确定要重置表单吗？所有数据将被清空。')) {
                $('#productionPlanForm')[0].reset();
                $('#productionItemsBody').empty();
                $('#attachmentsBody').empty();
                productionItemIndex = 0;
                attachmentIndex = 0;
                initializeForm();
            }
        }

        // 返回上一页
        function goBack() {
            if (confirm('确定要离开吗？未保存的数据将丢失。')) {
                window.location.href = '/Home/GetProductionPlan';
            }
        }

        // 显示加载状态
        function showLoading() {
            // 可以添加加载动画
            $('button[onclick="saveProductionPlan()"]').prop('disabled', true).html('<i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i> 保存中...');
        }

        // 隐藏加载状态
        function hideLoading() {
            $('button[onclick="saveProductionPlan()"]').prop('disabled', false).html('<i class="layui-icon layui-icon-ok"></i> 保存');
        }

        // 显示成功消息
        function showSuccess(message) {
            // 使用layui的提示框
            if (typeof layui !== 'undefined' && layui.layer) {
                layui.layer.msg(message, {icon: 1});
            } else {
                alert(message);
            }
        }

        // 显示错误消息
        function showError(message) {
            // 使用layui的提示框
            if (typeof layui !== 'undefined' && layui.layer) {
                layui.layer.msg(message, {icon: 2});
            } else {
                alert(message);
            }
        }
    </script>
}